package mx.org.banxico.sisal.servlets;

import cve.entidades.CVE;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mx.org.banxico.sisal.dao.VulnerabilityDAO;

public class VulnerabilityServlet extends HttpServlet implements java.io.Serializable {

    private static final long serialVersionUID = -1L;
    private static final Logger LOG = Logger.getLogger(VulnerabilityServlet.class.getName());

    public VulnerabilityServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        int page = 1;
        int recordsPerPage = 20;
        if (request.getParameter("page") != null) {
            LOG.log(Level.INFO, "El valor de page es: {0}", request.getParameter("page"));
            page = Integer.parseInt(request.getParameter("page"));
        }
        VulnerabilityDAO dao = new VulnerabilityDAO();
        //List<CVE> cveList = dao.retrieveAllCVEs((page - 1) * recordsPerPage, recordsPerPage);
        //List<CVE> cveList = dao.retrieveAllCVEsFromFile();
        LOG.log(Level.INFO, "Traeme registros del: {0} al: {1}", new Object[]{page - 1, recordsPerPage});
        List<CVE> cveList = dao.retrieveFromList((page - 1) * recordsPerPage, recordsPerPage);
        int noOfRecords = dao.getNoOfrecord();
        //int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        request.setAttribute("cveList", cveList);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        
        LOG.log(Level.INFO, "Redireccionando al recurso: /vulnerabilities/recentVulns.jsp");
        String nextJSP = "/admin/vulnerabilities/recentVulns.jsp";
        RequestDispatcher view = getServletContext().getRequestDispatcher(nextJSP);
        LOG.log(Level.INFO, "Servlet Context: {0}", getServletContext().toString());
        view.forward(request, response);
    }
}